package co.gov.medellin.ssti.sub.web.action;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.springframework.beans.factory.annotation.Autowired;

import co.gov.medellin.ssti.sub.common.excepcion.SUBException;
import co.gov.medellin.ssti.sub.model.dao.exception.DAOException;
import co.gov.medellin.ssti.sub.model.service.BeneficiarioService;
import co.gov.medellin.ssti.sub.model.service.ProgramaService;
import co.gov.medellin.ssti.sub.model.service.VflexService;
import co.gov.medellin.ssti.sub.model.vo.BeneficiarioVO;
import co.gov.medellin.ssti.sub.model.vo.ProgramaVO;
import co.gov.medellin.ssti.sub.model.vo.VflexVO;
import co.gov.medellin.ssti.sub.paoyer.administration.exception.AdministrationUserException;
import co.gov.medellin.ssti.sub.paoyer.administration.model.vo.UserVO;
import co.gov.medellin.ssti.sub.paoyer.administration.util.AccessControl;
import co.gov.medellin.ssti.sub.paoyer.common.exception.CommonUserException;
import co.gov.medellin.ssti.sub.paoyer.common.exception.UserException;
import co.gov.medellin.ssti.sub.web.form.ActualizarBeneficiarioForm;

public class ActualizarBeneficiarioAction extends Action {
	@Autowired
	BeneficiarioService beneficiarioServiceImpl;
	@Autowired
	ProgramaService programaServiceImpl;
	@Autowired
	VflexService vflexServiceImpl;

	/**
	 * This is the main action called from the Struts framework.
	 * 
	 * @param mapping
	 *            The ActionMapping used to select this instance.
	 * @param form
	 *            The optional ActionForm bean for this request.
	 * @param request
	 *            The HTTP Request we are processing.
	 * @param response
	 *            The HTTP Response we are processing.
	 * @return
	 * @throws java.io.IOException
	 * @throws javax.servlet.ServletException
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {

		ActionMessages messages = new ActionMessages();
		try {
			AccessControl access = new AccessControl();
			access.validateAccess(mapping, request, response);
			BeneficiarioVO objBeneVO = new BeneficiarioVO();

			ActualizarBeneficiarioForm actualizarForm = (ActualizarBeneficiarioForm) form;
			HttpSession session = request.getSession();
			objBeneVO.setCode(actualizarForm.getCode());
			objBeneVO.setTipoDocumento(actualizarForm.getTipoDocumento());
			objBeneVO.setNumeroDocumento(actualizarForm.getNumeroDocumento());
			objBeneVO.setNombre1(actualizarForm.getPrimer_nombre());
			objBeneVO.setNombre2(actualizarForm.getSegundo_nombre());
			objBeneVO.setPrimerApellido(actualizarForm.getPrimerApellido());
			objBeneVO.setSegundoApellido(actualizarForm.getSegundoApellido());

			objBeneVO.setHechoVictimizante(actualizarForm
					.getCodeHechoVictimizante());

			if (actualizarForm.getFechaNacimiento() != null
					&& actualizarForm.getFechaNacimiento().length() > 0) {
				objBeneVO.setFechaNacimiento(actualizarForm
						.getFechaNacimiento());
			} else {
				objBeneVO.setFechaNacimiento(null);
			}

			objBeneVO.setSexo(actualizarForm.getSexo());
			objBeneVO.setTelefono(actualizarForm.getTelefono());
			objBeneVO.setDirDescriptiva(actualizarForm.getDirDescriptiva());
			String dirEncasillada = actualizarForm.getDirEncasillada();
			objBeneVO.setDirEncasillada(dirEncasillada);
			objBeneVO.setCobama(actualizarForm.getCobama());
			objBeneVO.setVflComuna(actualizarForm.getVflComuna());
			objBeneVO.setCodeBarrio(actualizarForm.getCodeBarrio());
			objBeneVO.setCodeZona(actualizarForm.getCodeZona());
			objBeneVO.setEtnia(actualizarForm.getEtnia());
			objBeneVO.setMail(actualizarForm.getMail());

			// Para la auditoria de registros
			UserVO user = (UserVO) request.getSession(true).getAttribute(
					"userInfo");
			String terminalAddress = request.getRemoteAddr();
			objBeneVO.setUpdateUser(user.getName());
			objBeneVO.setUpdateTerminal("WEB=" + terminalAddress);
			Calendar c = Calendar.getInstance();
			SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
			objBeneVO.setUpdateDate(dateFormat.format(c.getTime()));

			int update = 0;
			try {
				update = beneficiarioServiceImpl.update(objBeneVO);
			} catch (DAOException e) {
				SUBException.logDebugError("", e);
			}
			if (update == 1) {
				session.setAttribute("actualizo", "true");
				session.removeAttribute("beneficiarios");

				request.setAttribute("msg", "");

				// Mostrar programas y subprogramas

				Collection<ProgramaVO> programas = null;

				ProgramaVO objProgramaVO = new ProgramaVO();
				try {
					programas = programaServiceImpl
							.findProgramaByCriteria(objProgramaVO);
				} catch (DAOException e) {
					SUBException.logDebugError("", e);
				}
				if (programas.size() > 0) {
					request.setAttribute("programas", programas);
				}

				return mapping.findForward("success");
			} else {
				try {
					Collection<VflexVO> comunas = vflexServiceImpl
							.findVflex(VflexService.COMUNA);
					Collection<VflexVO> barrios = vflexServiceImpl
							.findVflex(VflexService.BARRIO);
					Collection<VflexVO> zonas = vflexServiceImpl
							.findVflex(VflexService.ZONA);
					request.setAttribute("comunas", comunas);
					request.setAttribute("barrios", barrios);
					request.setAttribute("zonas", zonas);
				} catch (DAOException e) {
					SUBException.logDebugError("", e);
				}
				if (update == -1)
					request.setAttribute(
							"msg",
							"Ocurrio un error al actualizar el beneficiario: El documento ya fue registrado en el sistema");
				else
					request.setAttribute("msg",
							"Ocurrio un error al actualizar el beneficiario");

				request.setAttribute("beneficiario", objBeneVO);
				return mapping.findForward("fail");
			}

		} catch (UserException ue) {
			messages.add("msgWarn", new ActionMessage("loginForm.message."
					+ ue.getExceptionVO().getId()));
			saveMessages(request, messages);
			if (ue.getExceptionVO().getId() == AdministrationUserException.ENDED_SESSION) {
				response.sendRedirect(request.getContextPath() + "/index.jsp");
			} else if (ue.getExceptionVO().getId() == CommonUserException.NOT_ALLOWED_RESOURCE) {
				response.sendRedirect(request.getContextPath()
						+ "/admin/tile/invalidatedResource.jsp");
			} else {
				return mapping.getInputForward();
			}

		}

		return mapping.findForward("success");
	}
}